/*
 * schmitt.c
 *
 *  Created: 20250718
 *  Author: Hecate
 */
#include "schmitt.h"

#include <stdlib.h>

struct SchmittTrigger
{
    float upperThreshold;
    float lowerThreshold;
    uint8_t outputState;
};

SchmittTrigger *schmittInit(float upperThresh, float lowerThresh, uint8_t initState)
{
    SchmittTrigger *obj = (SchmittTrigger *) malloc(sizeof(SchmittTrigger));

    initState = (initState > 0) ? 1 : 0;  // 限制初始状态为0或1

    // 处理阈值逻辑
    if (upperThresh < lowerThresh)
    {
        // 下阈值大于上阈值时，交换二者
        obj->upperThreshold = lowerThresh;
        obj->lowerThreshold = upperThresh;
    }
    else
    {
        obj->upperThreshold = upperThresh;
        obj->lowerThreshold = lowerThresh;
    }

    // 设置初始状态
    obj->outputState = initState;

    return obj;
}

void schmittProcess(SchmittTrigger *obj, float inputValue)
{
    obj->outputState = obj->outputState ? ((inputValue <= obj->lowerThreshold) ? 0 : 1) : (inputValue >= obj->upperThreshold ? 1 : 0);
}

void schmittSetThresholds(SchmittTrigger *obj, float upperThresh, float lowerThresh)
{
    if (upperThresh < lowerThresh)
    {
        // 交换阈值
        obj->upperThreshold = lowerThresh;
        obj->lowerThreshold = upperThresh;
    }
    else
    {
        obj->upperThreshold = upperThresh;
        obj->lowerThreshold = lowerThresh;
    }
}

uint8_t schmittGetOutputState(const SchmittTrigger *obj)
{
    return obj->outputState;
}
